<template>
  <el-upload
      action="upload"
      :list-type="fileListType"
      :http-request="handleUploadFile"
      :on-remove="handleRemove"
      :before-upload="beforeUpload"
      :file-list="fileList"
      :limit="fileLimitSize"
      :on-exceed="handleExceed"
      >
      <i class="el-icon-plus" v-if="fileListType==='picture-card'"></i>
      <el-button size="small" type="primary" v-if="fileListType==='picture'">点击上传</el-button>
      <el-button size="small" type="primary" v-if="fileListType==='text'">点击上传</el-button>
  </el-upload>
</template>
<script>
export default {
    name: 'upload-pic',
    data () {
      return {
        fileSize: 0
      }
    },
    props: {
      fileList: {
        default: []
      },
      dir: {
        default: 'default'
      },
      fileMaxSize: {
        default: 5
      },
      fileLimitSize: {
        default: 5
      },
      fileListType: {
        default: 'picture-card'
      }
    },
    methods: {
      handleRemove(file, fileArray) {
        this.$emit('onChangeFilelist', fileArray);
      },
      handleExceed(files, fileArray) {
        this.$message.error('最多只能传' + this.fileLimitSize + '个文件');
      },
      beforeUpload (_file) {
        const isJpgPng = (_file.type === 'image/jpg' || _file.type === 'image/png' || _file.type === 'image/jpeg');
        const isLt5M = _file.size / 1024 / 1024 < this.fileMaxSize;
        if (!isJpgPng) {
          this.$message.error('上传图片只能是 JPG/PNG/JPEG 格式!');
          return false;
        }
        if (!isLt5M) {
          this.$message.error('上传图片大小不能超过 ' + this.fileMaxSize + 'MB!');
          return false;
        }
        return true;
      },
      handleUploadFile(params) {
        const _file = params.file
        this.$emit('upload', _file)
      }
    }
}
</script>